/*
 * 版权所有 (C) 2015 知启蒙(ZHIQIM) 保留所有权利。[遇见知启蒙，邂逅框架梦]
 * 
 * https://zhiqim.org/project/zhiqim_framework/zhiqim_ui.htm
 *
 * Zhiqim UI is licensed under Mulan PSL v2.
 * You can use this software according to the terms and conditions of the Mulan PSL v2.
 * You may obtain a copy of Mulan PSL v2 at:
 *          http://license.coscl.org.cn/MulanPSL2
 * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
 * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
 * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
 * See the Mulan PSL v2 for more details.
 */
 
+(function(Z)
{
//BEGIN

/****************************************/
//定义Z.Upload下的原型属性和方法
/****************************************/
Z.Upload = Z.Class.newInstance();
Z.Upload.prototype = 
{
    defaults:
    {
        elem: null,
        contextPath: null,
        onPreview: null,
        onCompleted: null,
        fileFormatExt: "*.*",
    },
    
    execute: function()
    {
        this.$elem = Z.$elem(this.elem, "Z.Upload");
        this.random = Z.random(10);
        this.text = this.$elem.text();
        
        this.$file = Z("<input id='Z_Upload_"+this.random+"' type='file' accept='"+this.fileFormatExt+"' class='z-hide' single>");
        this.$file.appendTo("body").change(this.onFileOpenWindow, this);
    
        this.$elem.click(function(){this.clear();this.$file[0].click();}, this);
    },
    
    onFileOpenWindow: function()
    {//打开文件选择窗口
        this.file = this.$file[0].files[0];
        
        if (!Z.T.isFunction(this.onPreview))
        {//不用预览直接上传
            this.upload();
        }
        else
        {//预览
            var reader = new FileReader();  
            reader.onload = Z.bind(function(event){
                this.onPreview(event.target.result);
            }, this);
            reader.readAsDataURL(this.file);  
        }
    },
    
    onUploadError: function()
    {
        //恢复和清理数据
        this.$elem.text(this.text);
        this.clear();
        
        alert("文件上传连接服务器失败："+this.request.responseText);
    },
    
    onUploadSuccess: function()
    {
        if (this.request.readyState != 4)
            return;
    
        //恢复和清理数据
        this.$elem.text(this.text);
        this.clear();

        switch(this.request.status)
        {
        case 404:alert("文件上传时服务器不支持");return;
        case 403:alert("文件上传时被服务器拒绝");return;
        case 412:alert("文件上传时服务器诊断参数格式错误");return;
        case 400:alert("文件上传时服务器诊断参数传值错误");return;
        case 200:
        {
            var fileUrl = this.request.getResponseHeader("X-Upload-File-Url");
            if (!fileUrl)
            {
                alert("文件上传时服务器异常");
                return;
            }
            
            if (Z.T.isFunction(this.onCompleted))
                this.onCompleted(fileUrl);
            return;
        }
        default:alert("文件上传时服务器未知错误："+this.request.status);return;
        }
    },

    upload: function()
    {
        this.$elem.text("正在上传");
        
        this.request = new XMLHttpRequest();
        this.request.open("POST", Z.rootPath(this.contextPath, "/service/upload"), true);
        this.request.setRequestHeader("Content-Type", this.file.type);
        this.request.setRequestHeader("Content-Length", this.file.size);
        if (this.fileDir)
            this.request.setRequestHeader("X-Upload-File-Dir", Z.encode(this.fileDir));
        this.request.setRequestHeader("X-Upload-File-Name", Z.encode(this.file.name));
        this.request.onreadystatechange = Z.bind(this.onUploadSuccess, this);
        this.request.onerror = Z.bind(this.onUploadError, this);
        this.request.send(this.file);
    },
    
    clear: function()
    {//清理
        this.$file[0].value = null;
        this.file = null;
    },
    
    /***********************************************************************************/
    //设置方法
    /***********************************************************************************/
        
    setFileDir: function(fileDir)
    {//设置上传的目录
        this.fileDir = fileDir;
        return this;
    },
    
    setFileFormatExt: function(fileFormatExt)
    {//设置上传的格式，如image/*
        this.fileFormatExt = fileFormatExt;
        return this;
    }
};

//END
})(zhiqim);